package com.ttctracker.map;

import java.util.Arrays;
import java.util.List;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ToggleButton;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.ttctracker.R;
import com.ttctracker.classes.Route;
import com.ttctracker.classes.StopItem;
import com.ttctracker.util.MyApp;
import com.ttctracker.util.SqlAdapter;

public class Map extends MapActivity {

	private MapView mapView;
	// private RoutePathOverlay pathOverlay;
	private RouteMapItemizedOverlay itemizedOverlay;
	private List<Overlay> mapOverlays;
	private MapController mController;
	private static final GeoPoint TORONTO_POINT = new GeoPoint(43653047,
			-79383425);
	private AutoCompleteTextView txtRouteSearch;
	private MyApp myApp;
	private Drawable drawableBusMarker;
	private String[] route_tags_keys, route_tags_titles;
	protected String selectedRoute;
	private ToggleButton btn_gps;
	private LocationManager locationManager;
	private Button btn_location;
	//private UserLocationHandler locationHandler;
	private static int locationUpdateInterval=1000*60;
	private static int locationUpdateDistance=500;
	private GetNearByRoutesTask getNearByRoutesTask;
	@Override
	protected void onCreate(Bundle icicle) {
		// TODO Auto-generated method stub
		super.onCreate(icicle);
		setContentView(R.layout.view_map);
		setupActivityResources();
		setupMapResources();

	}

		
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	private void setupActivityResources() {
		myApp = (MyApp) getApplication();
		route_tags_keys = myApp.getRoute_tags_keys();
		route_tags_titles = myApp.getRoute_tags_titles();
		txtRouteSearch = (AutoCompleteTextView) findViewById(R.id.txt_search_route_map);
		btn_gps = (ToggleButton) findViewById(R.id.btn_gps_route_map);
		btn_location = (Button) findViewById(R.id.btn_location_route_map);
		btn_location.setEnabled(false);

		txtRouteSearch.setAdapter(myApp.getRouteAdapter());
		txtRouteSearch.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int position, long arg3) {
				// myApp.hideKeyBoard(Map.this);
				MyApp.hideKeyBoard(Map.this, txtRouteSearch);
				txtRouteSearch.clearFocus();
				selectedRoute = route_tags_keys[Arrays.binarySearch(
						route_tags_titles,
						adapterView.getItemAtPosition(position))];
				btn_location.setEnabled(false);
				btn_gps.setChecked(false);
			//	removeLocationListener(false);
				new GetSelectedRouteTask().execute();

			}
		});

		txtRouteSearch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				((AutoCompleteTextView) v).selectAll();
				// myApp.popKeyBoard(Map.this);
			}
		});
		btn_gps.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					btn_location.setEnabled(true);
					if (getNearByRoutesTask==null) {
						getNearByRoutesTask=new GetNearByRoutesTask(Map.this,mapView,itemizedOverlay);
						getNearByRoutesTask.performSearch();
					}else {
						getNearByRoutesTask.startGPS();
						getNearByRoutesTask.performSearch();
					}
				//	requestLocationUpdate();

				} else {
					getNearByRoutesTask.stopGPS();
					if (btn_location.isEnabled()) {
						//removeLocationListener(true);
					} else {
						//removeLocationListener(false);
					}

				}

			}
		});

		btn_location.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				GeoPoint userLocation = itemizedOverlay.getUserLocation();
				if (userLocation != null) {
					mController.animateTo(userLocation);
				}
			}
		});
		// txtRouteSearch.requestFocus();
		// myApp.popKeyBoard(Map.this);
	}

	protected void onGPSDialogCancel() {
		if (!itemizedOverlay.gotUserLocation()) {
			btn_location.setEnabled(false);
			// removeLocationListener(false);
			btn_gps.setChecked(false);
		}else {
			btn_gps.setChecked(false);
		}

	}

/*	protected void removeLocationListener(boolean isSearchNearStop) {
		if (isSearchNearStop) {
			locationHandler.turningOffGPS(locationManager
					.getLastKnownLocation(LocationManager.GPS_PROVIDER));
		} else {
			locationHandler.turningOffGPS(null);
		}

		locationManager.removeUpdates(locationHandler);

	}

	protected void requestLocationUpdate() {
		locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, locationUpdateInterval,
				locationUpdateDistance, locationHandler);
		locationHandler.start(Map.this);
	}*/

	private void setupMapResources() {
		mapView = (MapView) findViewById(R.id.mapview);
		mapOverlays = mapView.getOverlays();
		mController = mapView.getController();
		mapView.setBuiltInZoomControls(true);
		mController.setZoom(15);
		mController.setCenter(TORONTO_POINT);
		mapOverlays = mapView.getOverlays();
		drawableBusMarker = this.getResources()
				.getDrawable(R.drawable.bus_icon);
		itemizedOverlay = new RouteMapItemizedOverlay(drawableBusMarker,
				mapView, this);
		// Set up resources used for GPS location
		//locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		//locationHandler = new UserLocationHandler(itemizedOverlay, mapView);
	}

	private class GetSelectedRouteTask extends AsyncTask<Void, Void, Route> {

		@Override
		protected Route doInBackground(Void... params) {
			try {
				SqlAdapter adapter = new SqlAdapter(Map.this);
				adapter.openDB();
				if (adapter.isOpen()) {
					Route result = adapter.selectRoute(Map.this.selectedRoute,
							true);
					adapter.close();
					return result;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Route result) {
			if (result != null) {
				itemizedOverlay.clear();
				itemizedOverlay.addSelectedRoute(result);
				StopItem[] stops = result.get_stopItems().values()
						.toArray(new StopItem[result.get_stopItems().size()]);
				RouteMapStopOverlayItem overlayItem = null;
				GeoPoint geoPoint = new GeoPoint(0, 0);
				for (StopItem stopItem : stops) {
					geoPoint = new GeoPoint((int) (stopItem.get_lat() * 1e6),
							(int) (stopItem.get_lon() * 1e6));
					overlayItem = new RouteMapStopOverlayItem(geoPoint,
							stopItem.get_title(),
							"Tap again to see predictions.", stopItem);
					itemizedOverlay.addOverlay(overlayItem);
				}
				StopItem centerStopItem = stops[stops.length / 2];
				geoPoint = new GeoPoint((int) (centerStopItem.get_lat() * 1e6),
						(int) (centerStopItem.get_lon() * 1e6));

				itemizedOverlay.populate_overlayItem();
				if (mapOverlays.size() == 0) {
					mapOverlays.add(itemizedOverlay);
				}
				mController.zoomToSpan(itemizedOverlay.getLatSpanE6(),
						itemizedOverlay.getLonSpanE6());
				mController.animateTo(itemizedOverlay.getCenter());

				mapView.invalidate();
			}
		}
	}
}
